package com.ruoyi.utils;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MapListUtil {

    /**
     * 计算满足条件的 total_amount 总和
     * @param dataList 数据列表
     * @param yesterdayValue yesterday 的期望值
     * @param parkTypeValue park_type 的期望值
     * @return 总和
     */
    public static double sumByConditions(List<Map<String, Object>> dataList,
                                         Object yesterdayValue,
                                         Object parkTypeValue) {
        return dataList.stream()
                .filter(map -> matchesCondition(map, "yesterday", yesterdayValue))
                .filter(map -> matchesCondition(map, "park_type", parkTypeValue))
                .mapToDouble(map -> safeGetDouble(map, "total_amount"))
                .sum();
    }

    /**
     * 检查Map中的值是否匹配条件
     */
    private static boolean matchesCondition(Map<String, Object> map, String key, Object expectedValue) {
        return Optional.ofNullable(map.get(key))
                .map(value -> String.valueOf(value).equals(String.valueOf(expectedValue)))
                .orElse(false);
    }

    /**
     * 安全地获取double值
     */
    private static double safeGetDouble(Map<String, Object> map, String key) {
        return Optional.ofNullable(map.get(key))
                .map(MapListUtil::parseDouble)
                .orElse(0.0);
    }

    /**
     * 解析各种类型的值为double
     */
    private static double parseDouble(Object value) {
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        try {
            return Double.parseDouble(String.valueOf(value));
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }
}
